package jt.classic.app.gdzc;

import jt.classic.system.ISystem;
import jt.classic.system.SimpleAction;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.databook.DataIndexManager;
import jt.classic.system.databook.IDataIndex;
import jt.classic.system.object.IObject;
import jt.classic.system.object.ObjectLCManager;
import jt.classic.system.object.ObjectManager;
import jt.classic.system.purview.PurviewManager;
import jt.classic.system.user.IUser;
import jt.classic.system.workflow.WObject;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.limp.basework.Column;
import org.limp.basework.Table;
import org.limp.basework.impl.CommonBean4HSQ;

import org.limp.mine.StringTool;
import org.limp.mine.annex.AnnexInfo;

import java.sql.Connection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 资产登记控制器
 * @author mido
 *
 */
public class GdzcAction extends SimpleAction {
    /**
    * 资产登记
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return ActionForward
    * @throws Exception
    */
    public ActionForward creategz(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        ActionForward forward = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map param = cbh.getResource();

        String type = (String) param.get("type");

        IUser user = ISystem.getSessionUser(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();

            conn = ds.getConnection();

            DataIndexManager dim = new DataIndexManager(conn);

            IDataIndex dataIndex = dim.getDataIndexById(type);

            if (dataIndex == null) {
                dataIndex = dim.getDataIndexByKey(type);
            }

            if (dataIndex == null) {
                request.setAttribute("error", "gztypeisnull");
                forward = mapping.findForward("gzerror");
            } else {
                request.setAttribute("dataIndex", dataIndex);
                forward = mapping.findForward("creategz");
            }
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
            forward = mapping.findForward("error");
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
     * 资产登记
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward neu(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        ActionForward forward = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map param = cbh.getResource();

        String id = StringTool.checkString(param.get("id"));

        IUser user = ISystem.getSessionUser(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();

            conn = ds.getConnection();

            GdzcTemplateManager gtmanager = new GdzcTemplateManager(conn);
            PurviewManager pmanager = new PurviewManager(conn);

            GdzcTemplate template = gtmanager.getTemplateById(id);

            if (template == null) {
                request.setAttribute("error", "gztempisempty");
                forward = mapping.findForward("gzerror");
            } else if (template.istatus() == -1) {
                request.setAttribute("error", "freeze");
                forward = mapping.findForward("gzerror");
            } else if (user.id().equals(template.iuserid()) ||
                    (pmanager.purview(id, "gztemp", user) == 3)) {
                request.setAttribute("template", template);
                forward = mapping.findForward("gzneu");
            } else {
                request.setAttribute("error", "noright");
                forward = mapping.findForward("gzerror");
            }
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
            forward = mapping.findForward("error");
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }

    /**
     * 资产编辑
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward edit(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map param = cbh.getResource();

        String id = StringTool.checkString(param.get("id"));

        IUser user = ISystem.getSessionUser(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();

            conn = ds.getConnection();

            ObjectManager manager = new ObjectManager(conn);

            ObjectLCManager lcmanager = new ObjectLCManager(conn);

            IObject object = lcmanager.getObjectById(id);

            if (object.iobject() == null) {
                request.setAttribute("result",
                    "{success: false, errCode : '-1'}");
            } else {
                if (manager.purview(id, user) < 2) {
                    request.setAttribute("result",
                        "{success: false, errCode : '-2'}");
                } else {
                    WObject obj = object.iobject();

                    String result = "{success: true, object:{oname:'" +
                        obj.iname() + "', okey:'" + obj.ikey() + "',ohandle:'" +
                        StringTool.checkString(obj.ieventhandler()) +
                        "',system:'" +
                        ((obj.isupport() != null) ? obj.isupport().ikey() : "") +
                        "',system1:'" +
                        ((obj.isupport() != null) ? obj.isupport().iname() : "") +
                        "'}";

                    StringBuffer resultStr = new StringBuffer();
                    resultStr.append(",core:{");
                    resultStr.append("okid:'" + object.id() + "',");
                    resultStr.append("oname:'" + object.iname() + "',");
                    resultStr.append("okey:'" + object.ikey() + "',");
                    resultStr.append("ocreatorid:'" + object.icreatorid() +
                        "',");
                    resultStr.append("ocreatorname:'" + object.icreatorname() +
                        "',");
                    resultStr.append("ounitid:'" +
                        object.getResource().get("OBJ_UNITID") + "',");
                    resultStr.append("ounitname:'" +
                        object.getResource().get("OBJ_UNITNAME") + "',");
                    resultStr.append("ounitnumber:'" +
                        object.getResource().get("OBJ_UNITNUMBER") + "',");
                    resultStr.append("ocreatetime:'" + object.icreatetime() +
                        "',");
                    resultStr.append("oupdatetime:'" + object.iupdatetime() +
                        "',");
                    resultStr.append("oremark:'" +
                        object.getResource().get("OBJ_REMARK") + "',");
                    resultStr.append("okeyword:'" + object.ikeyword() + "',");
                    resultStr.append("osummary:'" + object.isummary() + "',");
                    resultStr.append("osize:'" + object.size() + "'},data:");

                    List list = obj.itables();

                    Map dataContent = new HashMap();

                    if ((list != null) && !list.isEmpty()) {
                        Map annexItem = new HashMap();

                        for (int i = 0; i < list.size(); i++) {
                            Table table = (Table) list.get(i);

                            List columnList = table.columns();

                            Map info = (Map) ((List) object.icontent(table)).get(0);

                            for (int j = 0; j < columnList.size(); j++) {
                                Column column = (Column) columnList.get(j);

                                if (column.isAnnex() &&
                                        info.containsKey(column.getName())) {
                                    List annexList = new ArrayList();
                                    Map annexInfo = new HashMap();

                                    AnnexInfo[] annexs = (AnnexInfo[]) info.get(column.getName());

                                    for (int kk = 0; kk < annexs.length;
                                            kk++) {
                                        AnnexInfo ai = annexs[kk];
                                        annexInfo.put("id", ai.getID());
                                        annexInfo.put("name", ai.getName());
                                        annexList.add(annexInfo);
                                    }

                                    annexItem.put(column.getName(), annexList);
                                    dataContent.put(column.getName(), annexList);
                                } else {
                                    dataContent.put(column.getFormName(),
                                        StringTool.checkString(info.get(
                                                column.getName())));
                                }

                                if (table.getName().equals("APP_GDZC_WORDBOOK") &&
                                        (!column.isPremaryKey() &&
                                        (column.getName().indexOf("_ID") == -1) &&
                                        (column.getName().indexOf("_TYPE") == -1))) {
                                    dataContent.put(column.getFormName() + "_",
                                        StringTool.checkString(info.get(
                                                column.getName())));
                                } else if (table.getName().equals("APP_GDZC_DATAINDEX") &&
                                		(!column.isPremaryKey() &&
                                                (column.getName().indexOf("_ID") == -1) &&
                                                (column.getName().indexOf("_TYPE") == -1))) {
                                    dataContent.put(column.getFormName() + "_ID_",
                                        StringTool.checkString(info.get(
                                                column.getName())));
                                } else if (table.getName().equals("APP_GDZC_OBJECT") &&
                                		(!column.isPremaryKey() &&
                                                (column.getName().indexOf("_ID") == -1) &&
                                                (column.getName().indexOf("_TYPE") == -1))) {
                                    dataContent.put(column.getFormName() + "_ID_",
                                        StringTool.checkString(info.get(
                                                column.getName())));
                                }
                            }
                        }

                        dataContent.put("ANNEX", annexItem);
                    }

                    //JSONObject jsonObject = JSONArray.fromObject(dataContent);
                    JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(dataContent);

                    resultStr.append(jsonObject.toString());

                    result += resultStr.toString();
                    result += "}";

                    request.setAttribute("result", result);
                }
            }
        } catch (Exception ex) {
            ISystem.catchException(this, ex);

            request.setAttribute("result", "{success: false, errCode : '-3'}");
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 资产登记
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward gzlist(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;
        ActionForward forward = null;

        CommonBean4HSQ cbh = new CommonBean4HSQ(request);

        Map param = cbh.getResource();

        String type = (String) param.get("type");

        IUser user = ISystem.getSessionUser(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();

            conn = ds.getConnection();

            DataIndexManager dim = new DataIndexManager(conn);

            IDataIndex dataIndex = dim.getDataIndexById(type);

            if (dataIndex == null) {
                dataIndex = dim.getDataIndexByKey(type);
            }

            if (dataIndex == null) {
                request.setAttribute("error", "gztypeisnull");
                forward = mapping.findForward("gzerror");
            } else {
                request.setAttribute("dataIndex", dataIndex);
                forward = mapping.findForward("gzlist");
            }
        } catch (Exception ex) {
            ISystem.catchException(request, this, ex);
            forward = mapping.findForward("error");
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return forward;
    }
}
